package com.tensai.core.mvc.system.controller;

import com.tensai.core.mvc.base.tools.ResultJson;
import com.tensai.core.constant.ResponseStatus;
import com.tensai.core.mvc.system.entry.SysUser;
import com.tensai.core.mvc.system.service.ISysUserService;
import com.tensai.core.mvc.base.tools.SessionInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 前置controller
 *
 * @author Tensai
 * 2018/12/21
 */
@Slf4j
@Controller
@RequestMapping("/main")
public class IndexController {

    @Autowired
    private ISysUserService sysUserService;

    @RequestMapping("/login")
    @ResponseBody
    public ResultJson login(String username, String password, HttpServletRequest request) {
        SysUser user = sysUserService.login(username, password);
        if (user != null) {
            SessionInfo sessionInfo = new SessionInfo(user.getId(), user.getNickName());
            request.getSession().setAttribute("sessionInfo", sessionInfo);
            request.getSession().setAttribute("currentUser", user);
            request.getSession().setMaxInactiveInterval(24 * 60 * 60);
            Map<Object, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("nickName", user.getNickName());
            map.put("remark", user.getRemark());
            log.info("{} 请求登录成功，密码：{}", username, password);
            return new ResultJson(ResponseStatus.LOGIN_SUCCESS, map);
        } else {
            log.info("{} 请求登录失败，密码：{}", username, password);
            return new ResultJson(ResponseStatus.LOGIN_FAILURE);
        }
    }

    @RequestMapping("/autoLogin")
    @ResponseBody
    public ResultJson autoLogin(HttpServletRequest request) {
        SessionInfo sessionInfo = (SessionInfo) request.getSession().getAttribute("sessionInfo");
        if (sessionInfo != null) {
            if (sysUserService.findOne(sessionInfo.getUserId()) == null) {
                return new ResultJson(ResponseStatus.LOGIN_FAILURE);
            }
            return new ResultJson(ResponseStatus.LOGIN_SUCCESS);
        } else {
            return new ResultJson(ResponseStatus.LOGIN_FAILURE);
        }
    }

    @RequestMapping("/loginOut")
    @ResponseBody
    public ResultJson loginOut(HttpServletRequest request) {
        request.getSession().removeAttribute("sessionInfo");
        return new ResultJson(ResponseStatus.LOGOUT_SUCCESS);
    }

}

